<template>
  <div class="userpost-view">
    <div v-if="list" class="search-area">
      <search-card v-for="item in list.records" :key="item.id" :data="item">
        <template #ops>
          <el-popconfirm @confirm="handleDel(item.id)" title="你真的要删除吗?">
            <template #reference>
              <span class="userpost-btn"> 删除 </span>
            </template>
          </el-popconfirm>
          <span @click="handleEdit(item.id)" class="userpost-btn">编辑</span>
        </template>
      </search-card>
      <el-empty v-if="list.length === 0" />
    </div>
  </div>
  <el-pagination
    v-if="list"
    :page-size="list.size"
    :pager-count="list.pages"
    layout="prev, pager, next"
    :total="list.total"
    class="pagination"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { delPost, getUserPost } from '/src/api/post'
import { useUserStore } from '/src/store/user'
import SearchCard from '/src/components/SearchCard/index.vue'

const user = useUserStore()
const router = useRouter()
const list = ref(null)
const loaded = ref(false)
const handleDel = (pid) => {
  delPost(pid).then((res) => {
    const index = list.value.records.findIndex((v) => v.id === pid)
    console.log(index)
    list.value.records.splice(index, 1)
    loaded.value = true
    ElNotification({ type: 'success', message: res.msg })
  })
}
const handleEdit = (pid) => {
  router.push('/editor?type=post&id=' + pid)
}
if (user.hadLogin) {
  getUserPost(1, 4, user.uid).then((res) => (list.value = res.result))
}
function handleSizeChange(val) {
  getUserPost(val, list.value.size, user.uid).then((res) => (list.value = res.result))
  // console.log(`每页 ${val} 条`);
}
function handleCurrentChange(val) {
  getUserPost(val, list.value.size, user.uid).then((res) => (list.value = res.result))
  // console.log(`当前页: ${val}`);
}
</script>

<style lang="scss" scoped>
.userpost-view {
  height: 85%;
  overflow-y: auto;
}

.search-card:hover .userpost-btn {
  color: #1e80ff;
  visibility: visible;
}

.userpost-btn {
  margin: 6px;
  font-size: 14px;
  cursor: pointer;
  visibility: hidden;
}

.pagination {
  position: flex;
  justify-content: center;
}
</style>
